package com.snail.file.controller;

import com.snail.common.core.domain.R;
import com.snail.common.core.web.page.PageResult;
import com.snail.file.service.ISysFileService;
import com.snail.system.api.domain.SysFile;
import com.snail.system.api.query.SysFileQuery;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Delete;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 文件请求处理
 *
 * @author snail
 */
@Api(tags = "文件管理", value = "文件管理")
@RestController
@RequestMapping("/file")
public class SysFileController {
    private static final Logger log = LoggerFactory.getLogger(SysFileController.class);

    @Autowired
    private ISysFileService sysFileService;

    /**
     * 文件上传请求
     */
    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public R<SysFile> upload(@RequestPart("file") MultipartFile file,String bizKey) {
        try {
            return R.ok(sysFileService.uploadFile(file,bizKey));
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return R.fail(e.getMessage());
        }
    }

    @ApiOperation("分页查询文件信息")
    @GetMapping("/page")
    public R<PageResult<SysFile>> getSysFilePage(SysFileQuery query){
        return R.ok(sysFileService.getSysFilePage(query));
    }

    @ApiOperation("列表查询文件信息")
    @GetMapping("/list")
    public R<List<SysFile>> getSysFileList(SysFileQuery query){
        return R.ok(sysFileService.selectSysFileList(query));
    }

    @ApiOperation("文件下载")
    @GetMapping("/download/{fileId}")
    public void download(HttpServletResponse response,@PathVariable("fileId") String fileId){
        sysFileService.download(response,fileId);
    }

    @ApiOperation("删除文件")
    @DeleteMapping("/{fileId}")
    public R<Boolean> deleteFile(@PathVariable("fileId") String fileId){
        return R.ok(sysFileService.deleteFile(fileId));
    }
}